import React, { Component } from 'react';
import {
  Card,
  Timeline,
  Typography,
  Form,
  Input,
  Select,
  Radio,
  Space,
  Button,
  message,
} from 'antd';
import { router } from 'umi';
import { connect } from 'dva';
import LayerConfigProps from './layerConfigProps';
import { withRouter } from 'react-router-dom';
// 引入编辑器组件
import BraftEditor from 'braft-editor';
import UpLoadFile from './upLoadFile';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import { channelCdList } from './variable';
import { FormInstance } from 'antd/lib/form';
import { windowUrl } from '@/../public/global';
import { getToken, getMd5 } from '@/utils/utils';
import moment from 'moment';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface sendSelectType {
  value: string;
  label: string;
  [propName: string]: any;
}

const mapStateToProps = (state: any) => {
  return {
    messageTemplate: state.messageTemplate?.pageData,
    loading: state.loading.effects['messageTemplate/getFetchPage'],
  };
};

class messageTemplate_main extends Component<any, any> {
  state = {
    isLayer: false,
    fileUrl: '',
    radioVal: 0,
    editorState: '',
    sendList: [],
    channelCd: 99,
    isEditMsgCd: false,
  };

  layerData = {};
  layerForm = React.createRef<FormInstance>();
  formRef = React.createRef<FormInstance>();
  upLoadRef = React.createRef();

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { msgCd, projectId } = location?.query;
    this.setState({
      isEditMsgCd: msgCd ? true : false,
    });
    if (msgCd && projectId) {
      dispatch({
        type: 'messageTemplate/getFetchPage',
        payload: { url: '/message/template/findTemplateDetail', msgCd, projectId },
        callback: res => {
          const messageTemplate = res.data;
          const {
            // defaultPushChannel,
            channelCd,
            tplTitle,
            extraArgs,
            tplContent,
            tplType,
            senderId,
            // defaultSenderCd,
            attachments, //附件
            pushPeriod, //推送周期1实时2定时了间隔
            validityPeriod, // 有效期1永久有效2有效期至
            frequencyDay, // 推送评率天
            frequencyTimes, // 推送评率次
            interval, //间隔
            timer, //推送周期日期
            ackTimeout, //应答时长
            maxRepeat, //重发次数
            lengthStay, //驻留时长
            smsSignName, //短信签名
            expireTime, //有效期日期
          } = messageTemplate;

          const defaultType = tplType || 1;
          const channelCdVar = parseInt(channelCd) || 99;
          this.formRef.current?.setFieldsValue({
            channelCd: channelCdVar,
            tplTitle,
            msgCd,
            // tplContent,
            // attachments: '',
            tplType,
            ['tplContent' + defaultType]: tplContent,
            extraArgs: JSON.stringify(extraArgs),
          });

          const obj = {
            radioVal: tplType,
          };
          if (defaultType == 3) {
            Object.assign(obj, {
              editorState: BraftEditor.createEditorState(tplContent),
            });
          }
          this.setState(obj);
          this.layerData = {
            pushPeriod, //推送周期1实时2定时了间隔
            validityPeriod, // 有效期1永久有效2有效期至
            frequencyDay, // 推送评率天
            frequencyTimes, // 推送评率次
            interval, //间隔
            timer, //推送周期日期
            ackTimeout, //应答时长
            maxRepeat, //重发次数
            lengthStay, //驻留时长
            smsSignName, //短信签名
            expireTime,
          };
          // 附件
          this.upLoadRef.current.setData(attachments);
          // 联动
          this.typeChangeFn(channelCd, senderId);
        },
      });
    } else {
      this.typeChangeFn(99);
    }
  }
  // 跳转
  goChannelFn() {
    router.push('/messageCenter/messageChannelManagement');
  }
  // 返回
  goBackFn() {
    router.goBack();
  }
  // 提交
  onFinish = (val: any) => {
    const { dispatch } = this.props;
    const { msgCd, projectId } = this.props.location.query;
    const { messageTemplate } = this.props;
    const bool = msgCd && projectId && messageTemplate.id;
    const { extraArgs, tplType } = val;
    let newExtraArgs = {};
    try {
      if (extraArgs) {
        newExtraArgs = JSON.parse(extraArgs);
      }
    } catch (err) {
      console.log(err);
      message.error('扩展字段输入错误');
      return false;
    }

    const { fileList = [] } = this.upLoadRef?.current?.state;
    const attachments = fileList.map(e => {
      return {
        fileName: e.fileName || e.name,
        fileUrl: e.fileUrl || e.url || e?.response?.data?.fileUrl,
      };
    });

    const newTplContent = val['tplContent' + tplType];
    delete val['tplContent' + tplType];

    let payload = {
      url: '/message/template/updateTemplate',
      // ...messageTemplate,
      ...val,
      ...this.layerData,
      attachments,
      extraArgs: newExtraArgs,
      // interval: ,

      tplContent: newTplContent,
      // 测试数据给默认值5，记得删除
      approvalStatus: messageTemplate.releaseFlag || 3,
    };

    if (bool) {
      payload = {
        ...messageTemplate,
        ...payload,
        msgCd,
        projectId,
      };
    }

    dispatch({
      type: 'http/postObj',
      payload,
      callback: () => {
        router.goBack();
        message.success({
          content: `${bool ? '编辑' : '新增'}成功`,
        });
      },
    });
  };
  // 弹层确定
  handleOk = val => {
    this.layerData = {
      ...val,
    };

    this.handleCancel();
  };
  // 关闭
  handleCancel = () => {
    this.setState({
      isLayer: false,
    });
  };
  // 打开弹层
  clickConfigFn = () => {
    // 赋值 和显示
    this.setState(
      {
        isLayer: true,
      },
      () => {
        const { expireTime, timer } = this.layerData;
        const timeString = 'YYYY-MM-DD HH:mm:ss';
        function timeConversion(str) {
          if (!str) {
            return '';
          }
          const bool = isNaN(str * 1);
          return bool ? moment(str, timeString) : moment(str * 1);
        }
        this.layerForm.current.setData({
          ...this.layerData,
          expireTime: timeConversion(expireTime),
          timer: timeConversion(timer),
        });
      },
    );
  };
  uploadSuccess = (url: string) => {
    this.setState({
      fileUrl: url,
    });
  };
  onChange = (e: any) => {
    this.setState({
      radioVal: parseInt(e.target.value),
    });
  };
  handleEditorChange = (editorState: any) => {
    this.formRef.current?.setFieldsValue({
      tplContent3: editorState.toHTML(),
    });
  };
  uploadFn = param => {
    const serverURL = `${windowUrl}/upload/single?bizType=m18`;
    const xhr = new XMLHttpRequest();
    const fd = new FormData();
    let md5 = getMd5('bizType=m18')

    const successFn = response => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      // console.log(response,xhr);

      const obj = JSON.parse(xhr.responseText);
      if (obj.responseCode === '200') {
        const { fileRecordList } = obj || {};
        const data = fileRecordList[0];

        param.success({
          url: data.fileUri,
          // meta: {
          //   id: data.fileName,
          //   title: data.originalFileName,
          //   alt: data.originalFileName,
          //   loop: true, // 指定音视频是否循环播放
          //   autoPlay: true, // 指定音视频是否自动播放
          //   controls: true, // 指定音视频是否显示控制栏
          //   poster: data.coverPhoto || data.fileUri, // 指定视频播放器的封面
          // },
        });

        return false;
      }
      // 错误
      console.log(obj);
      param.error({
        msg: '上传失败',
      });
    };

    const progressFn = event => {
      // 上传进度发生变化时调用param.progress
      param.progress((event.loaded / event.total) * 100);
    };

    const errorFn = response => {
      // 上传发生错误时调用param.error
      param.error({
        msg: '上传失败.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);

    fd.append('file', param.file);
    xhr.open('POST', serverURL, true);
    xhr.setRequestHeader('OptAuthorization', `${getToken()}`);
    xhr.setRequestHeader('x-dfiov-fingerprint', sessionStorage.getItem('fingerprint') || 'undefined');
    xhr.setRequestHeader('shaSign', md5);
    xhr.send(fd);
  };
  typeChangeFn = (val: string | number, senderId: string = '') => {
    const channelCd = parseInt(val);
    const { dispatch } = this.props;

    if (!val) {
      return false;
    }
    dispatch({
      type: 'messageTemplate/getData',
      payload: {
        url: '/message/template/findSenderIdByChannelCd',
        channelCd,
      },
      callback: (res: any) => {
        const arr = res.data;
        let sendCd = '';
        arr.forEach((e: any) => {
          if (!sendCd) {
            const list = Object.keys(e);
            sendCd = list.find(e => e.includes('Cd')) as string;
          }
          e.value = e[sendCd];
          e.label = e[sendCd];
        });
        this.setState({
          sendList: arr,
          channelCd,
        });
        this.formRef.current?.setFieldsValue({
          senderId: senderId || null,
        });
      },
    });
  };
  validateFn = file => {
    console.log(file);
    return file.size < 1024 * 100;
  };
  // 弹层取消
  render() {
    const inpText = (
      <Form.Item name="tplContent1" label=" ">
        <Input.TextArea maxLength={1000} />
      </Form.Item>
    );
    const editorProps = {
      // height: this.props.height || 200,
      // contentFormat: 'html',
      // contentId:`${content}`,
      // initialContent: content!==undefined?`${content}`:'',
      // onChange: this.handleChange,
      // onRawChange: this.handleRawChange,
      // excludeControls: disabled ? ['emoji'] : [],
      fontFamilies: [
        {
          name: 'Araial',
          family: 'Arial, Helvetica, sans-serif',
        },
        {
          name: 'Georgia',
          family: 'Georgia, serif',
        },
        {
          name: 'Impact',
          family: 'Impact, serif',
        },
        {
          name: 'Monospace',
          family: '"Courier New", Courier, monospace',
        },
        {
          name: 'Tahoma',
          family: "tahoma, arial, 'Hiragino Sans GB', 宋体, sans-serif",
        },
        {
          name: '宋体',
          family: '宋体, sans-serif',
        },
        {
          name: '黑体',
          family: '黑体, sans-serif',
        },
        {
          name: '仿宋',
          family: '仿宋, sans-serif',
        },
        {
          name: 'Times New Roman',
          family: 'Times New Roman, sans-serif',
        },
      ],
      colors: [
        '#FF0000',
        '#FF6100',
        '#FFFF00',
        '#00FF00',
        '#00FFFF',
        '#0000FF',
        '#800080',
        '#000000',
        '#333333',
        '#666666',
        '#999999',
        '#cccccc',
        '#ffffff',
        '#EEE8AA',
        '#61a951',
        '#16a085',
        '#07a9fe',
        '#003ba5',
        '#8e44ad',
        '#f32784',
        '#FF7F50',
        '#c0392b',
        '#d35400',
        '#f39c12',
        '#fdda00',
        '#7f8c8d',
        '#2c3e50',
        '#A52A2A',
        '#87CEEB',
        '#00008B',
      ],
      media: {
        allowPasteImage: false, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
        image: true, // 开启图片插入功能
        video: true, // 开启视频插入功能
        audio: false, // 开启音频插入功能
        validateFn: null, // 指定本地校验函数，说明见下文
        // validateFn: this.validateFn, // 指定本地校验函数，说明见下文
        uploadFn: this.uploadFn, // 指定上传函数，说明见下文
        removeConfirmFn: null, // 指定删除前的确认函数，说明见下文
        onRemove: null, // 指定媒体库文件被删除时的回调，参数为被删除的媒体文件列表(数组)
        onChange: null, // 指定媒体库文件列表发生变化时的回调，参数为媒体库文件列表(数组)
        onInsert: null, // 指定从媒体库插入文件到编辑器时的回调，参数为被插入的媒体文件列表(数组)
        externalMedias: {
          image: true,
          audio: false,
          video: false,
          embed: false,
        },
      },
      onChange: this.handleEditorChange,
      value: this.state.editorState,
    };
    const inpTextArea = (
      <Form.Item name="tplContent3" label=" ">
        <div style={{ border: '1px solid #d9d9d9' }}>
          <BraftEditor
            // value={this.state.editorState}
            // onChange={this.handleEditorChange}
            // media={{ uploadFn: this.uploadFn }}
            // onSave={this.submitContent}
            {...editorProps}
          />
        </div>
      </Form.Item>
    );
    const { channelCd } = this?.state;
    return (
      <>
        <Card style={{ paddingLeft: '20px', paddingTop: '20px' }}>
          <Form
            style={{ maxWidth: '800px' }}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 14 }}
            colon={false}
            onFinish={this.onFinish}
            ref={this.formRef}
            initialValues={{ channelCd: 99 }}
          >
            <Timeline>
              <Timeline.Item>
                <Title level={4}>选择渠道</Title>
                <Form.Item
                  name="channelCd"
                  label="渠道类型："
                  rules={[{ required: true, message: '请选择渠道类型' }]}
                >
                  <Select placeholder="请选择" onChange={val => this.typeChangeFn(val)}>
                    {channelCdList.map(e => (
                      <Option value={e.value} key={e.value}>
                        {e.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                {channelCd != 99 && (
                  <Form.Item label="渠道发送方：" required>
                    <div style={{ display: 'flex' }}>
                      <Form.Item
                        name="senderId"
                        noStyle
                        rules={[{ required: true, message: '请选择渠道发送方' }]}
                      >
                        <Select placeholder="请选择">
                          {this.state.sendList.map((e: sendSelectType) => (
                            <Option key={e.value} value={e.value}>
                              {e.label}
                            </Option>
                          ))}
                        </Select>
                      </Form.Item>
                      <Button type="link" onClick={this.goChannelFn}>
                        暂无发送方，去新增
                      </Button>
                    </div>
                  </Form.Item>
                )}
              </Timeline.Item>
              <Timeline.Item>
                <Title level={4}>编辑内容</Title>
                <Form.Item
                  name="tplTitle"
                  label="模板名称："
                  rules={[{ required: true, message: '请输入模板名称' }]}
                >
                  <Input placeholder="请输入模板名称" maxLength={150} />
                </Form.Item>
                <Form.Item
                  name="msgCd"
                  label="模板编号："
                  rules={[{ required: true, message: '请输入模板编码' }]}
                >
                  <Input
                    placeholder="请输入模板编码"
                    disabled={this.state.isEditMsgCd}
                    maxLength={50}
                  />
                </Form.Item>
                <Form.Item
                  name="tplType"
                  label="模板内容："
                  rules={[{ required: true, message: '请输入模板内容' }]}
                >
                  <Radio.Group onChange={this.onChange}>
                    <Radio value={3}>富文本</Radio>
                    <Radio value={1}>纯文本</Radio>
                  </Radio.Group>
                </Form.Item>
                {this.state.radioVal === 3 ? inpTextArea : this.state.radioVal === 1 ? inpText : ''}
                <Form.Item name="nickname6" label=" ">
                  <UpLoadFile ref={this.upLoadRef} fileMaxSize={500}></UpLoadFile>
                </Form.Item>
                <Form.Item label=" ">
                  <Space direction="vertical">
                    <Text type="secondary">说明</Text>
                    <Text type="secondary">
                      {
                        ' 1.模板内容支持变量，消息发送时需将内容中的变量（如：${money}，${}内的money为变量）替换为参数值；'
                      }
                    </Text>
                    <Text type="secondary">
                      2.富文本中可插入图片、视频，图片、视频的插入位置在当前光标的停留处；
                    </Text>
                    <Text type="secondary">
                      3.附件支持格式有：gif,jpg,jpeg,png,bmp,swf,flv,mp,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4,txt,json,pdf,doc,docx,xls,xlsx,csv,ppt,pptx,vsd,vsdx,mpp,txt,htm,html,css,js,ts,less,zip,rar,gz,bz,7z,flac,ape,alac,mp3,aac,ogg,vorbis,opus；
                    </Text>
                  </Space>
                </Form.Item>
                <Form.Item name="extraArgs" label="扩展字段：">
                  <TextArea
                    rows={4}
                    placeholder={
                      '扩展字段可定义消息跳转规则、处理逻辑等，格式为JSON，例如：{"pageType":"navigation","longitude":112,"latitude":40}'
                    }
                    maxLength={500}
                  />
                </Form.Item>
              </Timeline.Item>
              <Timeline.Item>
                <Title level={4}>配置属性</Title>
                <Form.Item>
                  <Button type="text" onClick={this.clickConfigFn}>
                    {'配置消息属性>>'}
                    <Text type="secondary">（可选）</Text>
                  </Button>
                </Form.Item>
                <Form.Item label=" ">
                  <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button style={{ marginRight: '20px' }} onClick={this.goBackFn}>
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                      确认
                    </Button>
                  </div>
                </Form.Item>
              </Timeline.Item>
            </Timeline>
          </Form>
        </Card>
        {/* 弹层 */}
        <LayerConfigProps
          ref={this.layerForm}
          isLayer={this.state.isLayer}
          handleOk={this.handleOk}
          handleCancel={this.handleCancel}
        ></LayerConfigProps>
      </>
    );
  }
}
export default connect(mapStateToProps)(withRouter(messageTemplate_main));
